<?php
namespace app\common\process;

use think\exception\ValidateException;

class SubsidiaryOne extends Subsidiary {

    //获取从信息编辑
    public function info($user) {
        $model = $this->model;
        $validate = $this->validate;

        $ownerPk = input('param.' . $this->ownerPk);
        
        $this->validate_info($ownerPk, $user);

        $row = $model->where([$this->ownerPk => $ownerPk])->find();

        $this->assign($this->ownerPk, $ownerPk);
        $this->assign($this->row, $row);
        return $this->fetch();
    }

    //查看从信息公开信息，不验证权限
    public function look() {
        $model = $this->model;
        $validate = $this->validate;
        $ownerPk = input('param.' . $this->ownerPk);
        $this->validate_look($ownerPk);
        $row = $model->where([$this->ownerPk => $ownerPk])->find();
        if($row) {
            $row = $row->privacy()->toArray();
        }
        $this->assign($this->ownerPk, $ownerPk);
        $this->assign($this->row, $row);
        return $this->fetch();
    }

    

    //保存从信息
    public function save($user) {
        $model = $this->model;
        $validate = $this->validate;
        $pk = $this->pk;
        $ownerPk = $this->ownerPk;

        $post = $this->post($user);

        if (!$validate->scene($this->saveScene)->check($post)) {
            throw new ValidateException($validate->getError());
        }
        try {
            $model->startTrans();
            $this->trigger('before_save', [&$model, $post]);
            $data = $model->where([$ownerPk => $post[$ownerPk]])->find();
            if($data) {
                $model->allowField(true)->save($post, [$ownerPk => $post[$ownerPk]]);
            } else {
                $model->allowField(true)->save($post);
            }
            $this->trigger('after_save', [&$model, $post]);
            $model->commit();
        } catch(\Exception $e) {
            $model->rollback();
            $this->error($e);
        }
        $this->assign($ownerPk, $model->$ownerPk);
        return $this->fetch();
    }
}